// DBManager.java
package com.example.myapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;

public class DBManager {
    private DBHelper dbHelper;

    public DBManager(Context context) {
        dbHelper = new DBHelper(context);
    }

    // 添加所有汇率数据
    public void addAll(List<RateItem> rateItems) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            // 先删除旧数据
            db.delete(DBHelper.TABLE_NAME, null, null);

            // 插入新数据
            for (RateItem item : rateItems) {
                ContentValues cv = new ContentValues();
                cv.put("CURNAME", item.getCurrencyName());
                cv.put("CURRATE", item.getRateValue());
                db.insert(DBHelper.TABLE_NAME, null, cv);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
            db.close();
        }
    }

    // 获取所有汇率数据
    public List<RateItem> listAll() {
        List<RateItem> rateItems = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(DBHelper.TABLE_NAME,
                new String[]{"_id", "CURNAME", "CURRATE"},
                null, null, null, null, null);

        while (cursor.moveToNext()) {
            RateItem item = new RateItem();
            item.setId(cursor.getInt(0));
            item.setCurrencyName(cursor.getString(1));
            item.setRateValue(cursor.getDouble(2));
            rateItems.add(item);
        }
        cursor.close();
        db.close();
        return rateItems;
    }
}
